from rest_framework.exceptions import APIException
from rest_framework.views import exception_handler
from rest_framework.response import Response


class MagBaseException(APIException):
    """code < 100，前端配合清除Token，跳转到登录页"""
    code = 10000
    message = "未知异常，请联系管理员"

    @classmethod
    def get_message(self):
        return self.message


class InvalidUsernameOrPassword(MagBaseException):
    code = 1
    message = '用户名或密码错误'


class InvalidToken(MagBaseException):
    code = 2
    message = '登陆失效，请重新登陆'


class NotAuthenticated(MagBaseException):
    code = 3
    message = '未登录，请重新登录'


class InvalidPassword(MagBaseException):
    code = 101
    message = '旧密码错误'


class PermissionDeniedException(MagBaseException):
    code = 403
    message = '暂时无权限操作，请联系管理员'


class HugeFile(MagBaseException):
    code = 102
    message = "文件大小超过限制1KB"


exc_map = {
    'AuthenticationFailed': InvalidUsernameOrPassword,
    'InvalidToken': InvalidToken,  # token过期
    'NotAuthenticated': NotAuthenticated,  # 无token登录
    'InvalidPassword': InvalidPassword,
    'PermissionDenied': PermissionDeniedException,
    'HugeFile': HugeFile,
}


def global_exception_handler(exc, context):
    response = exception_handler(exc, context)  # 调用DRF缺省异常处理，返回Response对象或None
    if response is not None:
        exception = exc_map.get(exc.__class__.__name__, MagBaseException)  # 处理DRF异常
        error_message = exception.get_message()
        response_data = {
            'code': exception.code,
            'message': error_message
        }
        response = Response(response_data, status=200)
        return response
    return Response(exc.get_message(), status=200)  # 处理非DRF异常
